Page({
  data: {
    today: '',
    currentPlan: {}, // 当前要编辑的行程
    allSpots: [ // 景点列表（同新增页面）
      { id: 1, name: '相思湖湿地公园' },
      { id: 2, name: '创客小镇' },
      { id: 3, name: '文创街区' },
      { id: 4, name: '网红打卡点' },
      { id: 5, name: '特色美食街' },
      { id: 6, name: '亲子乐园' }
    ]
  },

  onLoad(options) {
    // 获取当前行程ID（从列表页传递）
    const { id } = options;
    // 加载当前行程数据
    this.loadCurrentPlan(id);
    // 设置今天日期
    const today = new Date().toISOString().split('T')[0];
    this.setData({ today });
  },

  // 加载当前要编辑的行程
  loadCurrentPlan(id) {
    const plans = wx.getStorageSync('xcjh_plans') || [];
    const currentPlan = plans.find(plan => plan.id === id);
    if (currentPlan) {
      this.setData({ currentPlan });
    } else {
      wx.showToast({ title: '行程不存在', icon: 'none' });
      setTimeout(() => wx.navigateBack(), 1500);
    }
  },

  // 处理标题修改
  handleTitleChange(e) {
    const currentPlan = { ...this.data.currentPlan, title: e.detail.value };
    this.setData({ currentPlan });
  },

  // 处理日期修改
  handleDateChange(e) {
    const currentPlan = { ...this.data.currentPlan, date: e.detail.value };
    this.setData({ currentPlan });
  },

  // 处理描述修改
  handleDescChange(e) {
    const currentPlan = { ...this.data.currentPlan, desc: e.detail.value };
    this.setData({ currentPlan });
  },

  // 切换景点选择
  toggleSpot(e) {
    const name = e.currentTarget.dataset.name;
    const currentPlan = { ...this.data.currentPlan };
    const index = currentPlan.spots.indexOf(name);
    
    if (index === -1) {
      currentPlan.spots.push(name);
    } else {
      currentPlan.spots.splice(index, 1);
    }
    
    this.setData({ currentPlan });
  },

  // 保存修改
  updatePlan() {
    const { currentPlan } = this.data;
    
    // 验证输入
    if (!currentPlan.title) {
      wx.showToast({ title: '请输入行程标题', icon: 'none' });
      return;
    }
    if (!currentPlan.date) {
      wx.showToast({ title: '请选择行程日期', icon: 'none' });
      return;
    }
    if (currentPlan.spots.length === 0) {
      wx.showToast({ title: '请至少选择一个景点', icon: 'none' });
      return;
    }

    // 更新本地存储中的行程
    let plans = wx.getStorageSync('xcjh_plans') || [];
    plans = plans.map(plan => 
      plan.id === currentPlan.id ? currentPlan : plan
    );
    wx.setStorageSync('xcjh_plans', plans);
    
    // 提示并返回列表页
    wx.showToast({ title: '行程修改成功' });
    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
  }
});